import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/restaurant_provider.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart'; // 使用新的SnackBar助手
import '../../models/restaurant.dart'; 
import 'add_edit_restaurant_screen.dart';
import 'restaurant_detail_screen.dart';

class RestaurantListScreen extends StatefulWidget {
  const RestaurantListScreen({super.key});

  @override
  State<RestaurantListScreen> createState() => _RestaurantListScreenState();
}

class _RestaurantListScreenState extends State<RestaurantListScreen> {
  @override
  void initState() {
    super.initState();
    // 页面初始化时加载饭店数据
    Future.microtask(() {
      Provider.of<RestaurantProvider>(context, listen: false).loadRestaurants();
    });
  }

  void _showDeleteDialog(BuildContext context, Restaurant restaurant) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除', style: AppTheme.titleMedium),
        content: Text(
          '确定要删除"${restaurant.name}"吗？',
          style: AppTheme.bodyMedium,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消', style: AppTheme.bodyMedium),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(ctx).pop();
              await _deleteRestaurant(restaurant);
            },
            child: const Text('删除', style: TextStyle(fontSize: 18, color: Colors.red)),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteRestaurant(Restaurant restaurant) async {
    try {
      final provider = Provider.of<RestaurantProvider>(context, listen: false);
      final success = await provider.deleteRestaurant(restaurant.id!);
      
      if (success) {
        // 使用SnackBar显示成功提示（底部绿色）
        SnackbarHelper.showSuccess(context, '已删除"${restaurant.name}"');
      } else {
        // 使用SnackBar显示错误提示（底部红色）
        SnackbarHelper.showError(context, '删除失败，请重试');
      }
    } catch (e) {
      SnackbarHelper.showError(context, '删除失败: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('饭店管理', style: AppTheme.titleLarge),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddEditRestaurantScreen(),
                ),
              );
            },
          ),
        ],
      ),
      body: Consumer<RestaurantProvider>(
        builder: (context, restaurantProvider, child) {
          if (restaurantProvider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          
          if (restaurantProvider.restaurants.isEmpty) {
            return Center(
              child: Text(
                '暂无饭店，请点击右上角"+"添加',
                style: AppTheme.bodyLarge,
                textAlign: TextAlign.center,
              ),
            );
          }

          return ListView.builder(
            itemCount: restaurantProvider.restaurants.length,
            itemBuilder: (context, index) {
              final restaurant = restaurantProvider.restaurants[index];
              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                child: ListTile(
                  contentPadding: const EdgeInsets.all(16),
                  title: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        restaurant.name,
                        style: AppTheme.titleMedium,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 8),
                      if (restaurant.contact != null && restaurant.contact!.isNotEmpty)
                        Text(
                          '联系人: ${restaurant.contact!}',
                          style: AppTheme.bodyMedium,
                        ),
                      const SizedBox(height: 4),
                      if (restaurant.address != null && restaurant.address!.isNotEmpty)
                        Text(
                          '地址: ${restaurant.address!}',
                          style: AppTheme.bodySmall,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                    ],
                  ),
                  trailing: SizedBox(
                    width: 160,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        // 编辑按钮 - 使用文字
                        ElevatedButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => AddEditRestaurantScreen(
                                  restaurant: restaurant,
                                ),
                              ),
                            );
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue[700],
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          ),
                          child: const Text(
                            '编辑',
                            style: TextStyle(fontSize: 16, color: Colors.white),
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 删除按钮 - 使用文字
                        ElevatedButton(
                          onPressed: () => _showDeleteDialog(context, restaurant),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red[700],
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          ),
                          child: const Text(
                            '删除',
                            style: TextStyle(fontSize: 16, color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    // 点击进入饭店详情页（商品管理）
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => RestaurantDetailScreen(
                          restaurant: restaurant,
                        ),
                      ),
                    );
                  },
                
                ),
              );
            },
          );
        },
      ),
    );
  }
}